//
//  YYActionSheetView.swift
//  CodeLibrary_Swift
//
//  Created by 陆文宇 on 2017/5/26.
//  Copyright © 2017年 陆文宇. All rights reserved.
//

import UIKit

class YYActionSheetCell: UICollectionViewCell {
    
    var titleLabel: UILabel!
    var imageView: UIImageView!
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        imageView = UIImageView(frame: CGRect(x: 10, y: 0, width: frame.width - 20, height: frame.width - 20))
        titleLabel = UILabel(frame: CGRect(x: 0, y: frame.width, width: frame.width, height: frame.height - frame.width))
        titleLabel.textAlignment = .center
        titleLabel.font = UIFont.systemFont(ofSize: 15)
        
        contentView.addSubview(titleLabel)
        contentView.addSubview(imageView)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

class YYActionSheetAction {
    var title: String
    var image: UIImage?
    var action: () -> Void
    
    init(title: String, image: UIImage, action: @escaping () -> Void) {
        self.title = title
        self.image = image
        self.action = action
    }
}

class YYActionSheetView: UIView, UICollectionViewDelegate, UICollectionViewDataSource {
    
    var actionView: UIView!
    var titleLabel: UILabel!
    var collectionView: UICollectionView!
    
    var title: String {
        willSet {
            titleLabel.text = newValue
        }
    }
    private(set) var actions: [YYActionSheetAction] = []
    
    init(title: String = "") {
        self.title = title
        super.init(frame: UIScreen.main.bounds)
        
        let backV = UIView(frame: UIScreen.main.bounds)
        backV.backgroundColor = .clear
        let dismissTap = UITapGestureRecognizer(target: self, action: #selector(dismissAction))
        backV.addGestureRecognizer(dismissTap)
        
        titleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 100), aFont: UIFont.systemFont(ofSize: 13), aString: title)
        titleLabel.backgroundColor = .white
        titleLabel.frame.size.height += 20
        titleLabel.textAlignment = .center
        
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = CGSize(width: 80, height: 90)
        layout.minimumLineSpacing = 20
        layout.minimumInteritemSpacing = 20
        layout.scrollDirection = .horizontal
        layout.sectionInset = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20)
        collectionView = UICollectionView(frame: CGRect(x: 0, y: titleLabel.frame.height + 1, width: UIScreen.main.bounds.width, height: 150), collectionViewLayout: layout)
        collectionView.backgroundColor = .white
        collectionView.dataSource = self
        collectionView.delegate = self
        
        let cancelButton = UIButton(type: .system)
        cancelButton.frame = CGRect(x: 0, y: titleLabel.frame.height + 1 + 150 + 5, width: UIScreen.main.bounds.width, height: 40)
        cancelButton.backgroundColor = .white
        cancelButton.setTitle("取消", for: .normal)
        cancelButton.setTitleColor(.black, for: .normal)
        cancelButton.addTarget(self, action: #selector(dismissAction), for: .touchUpInside)
        
        actionView = UIView(frame: CGRect(x: 0, y: UIScreen.main.bounds.height, width: UIScreen.main.bounds.width, height: titleLabel.frame.height + 1 + 150 + 5 + 30))
        actionView.backgroundColor = UIColor(white: 0.93, alpha: 1)
        actionView.addSubview(titleLabel)
        actionView.addSubview(collectionView)
        actionView.addSubview(cancelButton)
        
        addSubview(backV)
        addSubview(actionView)
        
        collectionView.register(YYActionSheetCell.self, forCellWithReuseIdentifier: "actionCell")
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func addAction(_ action: YYActionSheetAction) -> Void {
        actions.append(action)
    }
    
    func show() {
        if superview == nil {
            UIApplication.shared.keyWindow?.addSubview(self)
            
            UIView.animate(withDuration: 0.3, animations: {
                self.actionView.superview?.backgroundColor = UIColor.gray.withAlphaComponent(0.9)
                self.actionView.transform = CGAffineTransform(translationX: 0, y: -(self.titleLabel.frame.height + 196))
            })
        }
    }
    
    @objc func dismissAction() {
        dismiss()
    }
    
    func dismiss(completionHandler: (() -> Void)? = nil) {
        if superview != nil {
            UIView.animate(withDuration: 0.3, animations: {
                self.actionView.superview?.backgroundColor = .clear
                self.actionView.transform = CGAffineTransform.identity
            }, completion: { (_) in
                self.removeFromSuperview()
                completionHandler?()
            })
        }
    }
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return actions.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "actionCell", for: indexPath) as! YYActionSheetCell
        let action = actions[indexPath.item]
        cell.titleLabel.text = action.title
        cell.imageView.image = action.image
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        dismiss {
            self.actions[indexPath.item].action()
        }
    }
    
    /*
     // Only override draw() if you perform custom drawing.
     // An empty implementation adversely affects performance during animation.
     override func draw(_ rect: CGRect) {
     // Drawing code
     }
     */
    
}

